<template>
  <div class="home-settings">
    <div class="page-header">
      <h1>首页配置管理</h1>
      <el-button type="primary" @click="initSettings" :loading="loading">
        <el-icon><RefreshRight /></el-icon>
        初始化默认配置
      </el-button>
    </div>

    <el-tabs v-model="activeTab" type="card">
      <!-- 顶部区域配置 -->
      <el-tab-pane label="顶部区域" name="hero">
        <el-card>
          <el-form :model="settings" label-width="140px">
            <!-- 背景图片 -->
            <el-form-item label="背景图片">
              <div class="image-upload-container">
                <el-upload
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :http-request="(file) => uploadImage(file, 'homepage_hero_background')"
                  accept="image/*"
                >
                  <img 
                    v-if="settings.homepage_hero_background" 
                    :src="settings.homepage_hero_background" 
                    class="upload-preview"
                  />
                  <div v-else class="upload-placeholder">
                    <el-icon><Plus /></el-icon>
                    <span>上传背景图片</span>
                  </div>
                </el-upload>
                <div class="upload-tips">
                  <p>建议尺寸：1920x600px</p>
                  <p>支持 JPG、PNG 格式</p>
                </div>
              </div>
            </el-form-item>

            <!-- Logo图片 -->
            <el-form-item label="Logo图片">
              <div class="image-upload-container">
                <el-upload
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :http-request="(file) => uploadImage(file, 'homepage_logo')"
                  accept="image/*"
                >
                  <img 
                    v-if="settings.homepage_logo" 
                    :src="settings.homepage_logo" 
                    class="upload-preview small"
                  />
                  <div v-else class="upload-placeholder small">
                    <el-icon><Plus /></el-icon>
                    <span>上传Logo</span>
                  </div>
                </el-upload>
                <div class="upload-tips">
                  <p>建议尺寸：200x60px</p>
                  <p>支持 JPG、PNG 格式</p>
                </div>
              </div>
            </el-form-item>

            <!-- 公司名称（三语言） -->
            <el-form-item label="公司名称（英文）">
              <el-input 
                v-model="settings.homepage_company_name_en" 
                placeholder="输入英文公司名称"
              />
            </el-form-item>
            <el-form-item label="公司名称（西班牙语）">
              <el-input 
                v-model="settings.homepage_company_name_es" 
                placeholder="输入西班牙语公司名称"
              />
            </el-form-item>
            <el-form-item label="公司名称（日语）">
              <el-input 
                v-model="settings.homepage_company_name_ja" 
                placeholder="输入日语公司名称"
              />
            </el-form-item>

            <!-- 质量认证图标 -->
            <el-form-item label="质量认证图标">
              <div class="certifications-container">
                <div 
                  v-for="(cert, index) in certifications" 
                  :key="index"
                  class="certification-item"
                >
                  <el-upload
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :http-request="(file) => uploadCertification(file, index)"
                    accept="image/*"
                  >
                    <img 
                      v-if="cert.image" 
                      :src="cert.image" 
                      class="cert-preview"
                    />
                    <div v-else class="cert-placeholder">
                      <el-icon><Plus /></el-icon>
                    </div>
                  </el-upload>
                  <el-input 
                    v-model="cert.name" 
                    placeholder="认证名称"
                    size="small"
                  />
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeCertification(index)"
                  >
                    删除
                  </el-button>
                </div>
                <el-button 
                  type="primary" 
                  @click="addCertification"
                  size="small"
                >
                  <el-icon><Plus /></el-icon>
                  添加认证
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 产品展示区域配置 -->
      <el-tab-pane label="产品展示" name="products">
        <el-card>
          <el-form :model="settings" label-width="140px">
            <!-- 产品区域标题 -->
            <el-form-item label="区域标题（英文）">
              <el-input 
                v-model="settings.homepage_products_title_en" 
                placeholder="输入英文标题"
              />
            </el-form-item>
            <el-form-item label="区域标题（西班牙语）">
              <el-input 
                v-model="settings.homepage_products_title_es" 
                placeholder="输入西班牙语标题"
              />
            </el-form-item>
            <el-form-item label="区域标题（日语）">
              <el-input 
                v-model="settings.homepage_products_title_ja" 
                placeholder="输入日语标题"
              />
            </el-form-item>

            <!-- 6个产品配置 -->
            <div v-for="i in 6" :key="i" class="product-config">
              <h3>产品 {{ i }}</h3>
              <el-form-item :label="`产品${i}图片`">
                <div class="image-upload-container">
                  <el-upload
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :http-request="(file) => uploadImage(file, `homepage_product_${i}_image`)"
                    accept="image/*"
                  >
                    <img 
                      v-if="settings[`homepage_product_${i}_image`]" 
                      :src="settings[`homepage_product_${i}_image`]" 
                      class="upload-preview round"
                    />
                    <div v-else class="upload-placeholder round">
                      <el-icon><Plus /></el-icon>
                      <span>上传产品图片</span>
                    </div>
                  </el-upload>
                  <div class="upload-tips">
                    <p>建议尺寸：300x300px</p>
                    <p>圆形展示效果</p>
                  </div>
                </div>
              </el-form-item>
              <el-form-item :label="`产品${i}名称（英文）`">
                <el-input 
                  v-model="settings[`homepage_product_${i}_name_en`]" 
                  placeholder="输入英文名称"
                />
              </el-form-item>
              <el-form-item :label="`产品${i}名称（西班牙语）`">
                <el-input 
                  v-model="settings[`homepage_product_${i}_name_es`]" 
                  placeholder="输入西班牙语名称"
                />
              </el-form-item>
              <el-form-item :label="`产品${i}名称（日语）`">
                <el-input 
                  v-model="settings[`homepage_product_${i}_name_ja`]" 
                  placeholder="输入日语名称"
                />
              </el-form-item>
            </div>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- About Us 区域配置 -->
      <el-tab-pane label="About Us" name="about">
        <el-card>
          <el-form :model="settings" label-width="140px">
            <!-- About Us标题 -->
            <el-form-item label="标题（英文）">
              <el-input 
                v-model="settings.homepage_about_title_en" 
                placeholder="输入英文标题"
              />
            </el-form-item>
            <el-form-item label="标题（西班牙语）">
              <el-input 
                v-model="settings.homepage_about_title_es" 
                placeholder="输入西班牙语标题"
              />
            </el-form-item>
            <el-form-item label="标题（日语）">
              <el-input 
                v-model="settings.homepage_about_title_ja" 
                placeholder="输入日语标题"
              />
            </el-form-item>

            <!-- About Us内容 -->
            <el-form-item label="内容（英文）">
              <el-input 
                type="textarea"
                :rows="4"
                v-model="settings.homepage_about_content_en" 
                placeholder="输入英文内容"
              />
            </el-form-item>
            <el-form-item label="内容（西班牙语）">
              <el-input 
                type="textarea"
                :rows="4"
                v-model="settings.homepage_about_content_es" 
                placeholder="输入西班牙语内容"
              />
            </el-form-item>
            <el-form-item label="内容（日语）">
              <el-input 
                type="textarea"
                :rows="4"
                v-model="settings.homepage_about_content_ja" 
                placeholder="输入日语内容"
              />
            </el-form-item>

            <!-- About Us图片 -->
            <el-form-item label="右侧图片">
              <div class="image-upload-container">
                <el-upload
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :http-request="(file) => uploadImage(file, 'homepage_about_image')"
                  accept="image/*"
                >
                  <img 
                    v-if="settings.homepage_about_image" 
                    :src="settings.homepage_about_image" 
                    class="upload-preview"
                  />
                  <div v-else class="upload-placeholder">
                    <el-icon><Plus /></el-icon>
                    <span>上传About Us图片</span>
                  </div>
                </el-upload>
                <div class="upload-tips">
                  <p>建议尺寸：400x300px</p>
                  <p>支持 JPG、PNG 格式</p>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 视频配置 -->
      <el-tab-pane label="视频配置" name="video">
        <el-card>
          <el-form :model="settings" label-width="140px">
            <!-- 视频上传 -->
            <el-form-item label="首页展示视频">
              <div class="video-upload-container">
                <el-upload
                  :show-file-list="false"
                  :before-upload="beforeVideoUpload"
                  :http-request="(file) => uploadVideo(file, 'homepage_video_url')"
                  accept="video/*"
                >
                  <div class="video-upload-area">
                    <video 
                      v-if="settings.homepage_video_url" 
                      :src="settings.homepage_video_url" 
                      class="video-preview"
                      controls
                    />
                    <div v-else class="upload-placeholder">
                      <el-icon><VideoPlay /></el-icon>
                      <span>上传视频文件</span>
                    </div>
                  </div>
                </el-upload>
                <div class="upload-tips">
                  <p>建议格式：MP4、WebM</p>
                  <p>建议尺寸：1920x1080px</p>
                  <p>文件大小：不超过100MB</p>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 流程步骤配置 -->
      <el-tab-pane label="流程步骤" name="steps">
        <el-card>
          <div class="steps-header">
            <h3>流程步骤管理</h3>
            <el-button type="primary" @click="addProcessStep">
              <el-icon><Plus /></el-icon>
              添加步骤
            </el-button>
          </div>
          
          <div class="steps-list">
            <div 
              v-for="(step, index) in processSteps" 
              :key="step.step"
              class="step-card"
            >
              <div class="step-header">
                <span class="step-number">步骤 {{ step.step }}</span>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeProcessStep(index)"
                  :icon="Delete"
                >
                  删除
                </el-button>
              </div>
              
              <el-form :model="step" label-width="100px">
                <!-- 步骤图标 -->
                <el-form-item label="步骤图标">
                  <div class="icon-upload-container">
                    <el-upload
                      :show-file-list="false"
                      :before-upload="beforeUpload"
                      :http-request="(file) => uploadStepIcon(file, index)"
                      accept="image/*"
                    >
                      <img 
                        v-if="step.icon" 
                        :src="step.icon" 
                        class="icon-preview"
                      />
                      <div v-else class="icon-placeholder">
                        <el-icon><Picture /></el-icon>
                        <span>上传图标</span>
                      </div>
                    </el-upload>
                  </div>
                </el-form-item>

                <!-- 多语言标题 -->
                <el-form-item label="标题(英文)">
                  <el-input v-model="step.title_en" placeholder="请输入英文标题" />
                </el-form-item>
                <el-form-item label="标题(西班牙语)">
                  <el-input v-model="step.title_es" placeholder="请输入西班牙语标题" />
                </el-form-item>
                <el-form-item label="标题(日语)">
                  <el-input v-model="step.title_ja" placeholder="请输入日语标题" />
                </el-form-item>

                <!-- 多语言描述 -->
                <el-form-item label="描述(英文)">
                  <el-input 
                    v-model="step.description_en" 
                    type="textarea" 
                    placeholder="请输入英文描述"
                    :rows="3"
                  />
                </el-form-item>
                <el-form-item label="描述(西班牙语)">
                  <el-input 
                    v-model="step.description_es" 
                    type="textarea" 
                    placeholder="请输入西班牙语描述"
                    :rows="3"
                  />
                </el-form-item>
                <el-form-item label="描述(日语)">
                  <el-input 
                    v-model="step.description_ja" 
                    type="textarea" 
                    placeholder="请输入日语描述"
                    :rows="3"
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 底部保存按钮 -->
    <div class="footer-actions">
      <el-button type="primary" @click="saveSettings" :loading="saving">
        <el-icon><Check /></el-icon>
        保存配置
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { request } from '../../utils/request'
import { Plus, RefreshRight, Check, Delete, VideoPlay, Picture } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadRequestOptions } from 'element-plus'

interface Certification {
  name: string
  image: string
  order: number
}

interface ProcessStep {
  step: number
  title_en: string
  title_es: string
  title_ja: string
  description_en: string
  description_es: string
  description_ja: string
  icon: string
}

const activeTab = ref('hero')
const loading = ref(false)
const saving = ref(false)
const settings = reactive<Record<string, any>>({})
const certifications = ref<Certification[]>([])
const processSteps = ref<ProcessStep[]>([])

// 获取系统设置
const getSettings = async () => {
  loading.value = true
  try {
    const response = await request.get('/settings')
    if (response.success) {
      // 将数组转换为对象
      response.data.forEach((item: any) => {
        if (item.key === 'homepage_certifications') {
          try {
            certifications.value = JSON.parse(item.value)
          } catch {
            certifications.value = []
          }
        } else if (item.key === 'homepage_process_steps') {
          try {
            processSteps.value = JSON.parse(item.value)
          } catch {
            processSteps.value = []
          }
        } else {
          settings[item.key] = item.value
        }
      })
    }
  } catch (error) {
    ElMessage.error('获取配置失败')
  } finally {
    loading.value = false
  }
}

// 初始化默认设置
const initSettings = async () => {
  try {
    await ElMessageBox.confirm(
      '初始化将创建默认配置，已有配置不会被覆盖。是否继续？',
      '确认初始化',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    const response = await request.post('/settings/init')
    if (response.success) {
      ElMessage.success('初始化成功')
      getSettings()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('初始化失败')
    }
  } finally {
    loading.value = false
  }
}

// 保存设置
const saveSettings = async () => {
  saving.value = true
  try {
    // 准备要保存的数据
    const dataToSave = {
      ...settings,
      homepage_certifications: JSON.stringify(certifications.value),
      homepage_process_steps: JSON.stringify(processSteps.value)
    }

    const response = await request.post('/settings/batch', {
      settings: dataToSave
    })

    if (response.success) {
      ElMessage.success('保存成功')
    }
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 图片上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 上传图片
const uploadImage = async (options: UploadRequestOptions, key: string) => {
  const formData = new FormData()
  formData.append('file', options.file)

  try {
    const response = await request.post('/settings/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.success) {
      settings[key] = response.data.url
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

// 上传认证图标
const uploadCertification = async (options: UploadRequestOptions, index: number) => {
  const formData = new FormData()
  formData.append('file', options.file)

  try {
    const response = await request.post('/settings/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.success) {
      certifications.value[index].image = response.data.url
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

// 添加认证
const addCertification = () => {
  certifications.value.push({
    name: '',
    image: '',
    order: certifications.value.length + 1
  })
}

// 删除认证
const removeCertification = (index: number) => {
  certifications.value.splice(index, 1)
  // 重新排序
  certifications.value.forEach((cert, idx) => {
    cert.order = idx + 1
  })
}

// 视频上传前验证
const beforeVideoUpload = (file: File) => {
  const isVideo = file.type.startsWith('video/')
  const isLt100M = file.size / 1024 / 1024 < 100

  if (!isVideo) {
    ElMessage.error('只能上传视频文件!')
    return false
  }
  if (!isLt100M) {
    ElMessage.error('视频文件大小不能超过100MB!')
    return false
  }
  return true
}

// 上传视频
const uploadVideo = async (options: UploadRequestOptions, settingKey: string) => {
  const formData = new FormData()
  formData.append('file', options.file)

  try {
    const response = await request.post('/settings/upload/media', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    
    if (response.success) {
      settings[settingKey] = response.data.url
      ElMessage.success('视频上传成功')
    }
  } catch (error) {
    ElMessage.error('视频上传失败')
  }
}

// 添加流程步骤
const addProcessStep = () => {
  const newStep: ProcessStep = {
    step: processSteps.value.length + 1,
    title_en: '',
    title_es: '',
    title_ja: '',
    description_en: '',
    description_es: '',
    description_ja: '',
    icon: ''
  }
  processSteps.value.push(newStep)
}

// 删除流程步骤
const removeProcessStep = (index: number) => {
  ElMessageBox.confirm(
    '确定要删除这个步骤吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    processSteps.value.splice(index, 1)
    // 重新编号
    processSteps.value.forEach((step, idx) => {
      step.step = idx + 1
    })
    ElMessage.success('删除成功')
  })
}

// 上传步骤图标
const uploadStepIcon = async (options: UploadRequestOptions, stepIndex: number) => {
  const formData = new FormData()
  formData.append('file', options.file)

  try {
    const response = await request.post('/settings/upload/image', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    
    if (response.success) {
      processSteps.value[stepIndex].icon = response.data.url
      ElMessage.success('图标上传成功')
    }
  } catch (error) {
    ElMessage.error('图标上传失败')
  }
}

onMounted(() => {
  getSettings()
})
</script>

<style scoped>
.home-settings {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.footer-actions {
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 4px;
  text-align: center;
}

.image-upload-container {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.upload-preview {
  width: 200px;
  height: 120px;
  object-fit: cover;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
}

.upload-preview.small {
  width: 120px;
  height: 60px;
}

.upload-preview.round {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}

.upload-placeholder {
  width: 200px;
  height: 120px;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.upload-placeholder.small {
  width: 120px;
  height: 60px;
}

.upload-placeholder.round {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}

.upload-placeholder:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-placeholder .el-icon {
  font-size: 28px;
  color: #909399;
  margin-bottom: 5px;
}

.upload-placeholder span {
  font-size: 14px;
  color: #909399;
}

.upload-tips {
  flex: 1;
}

.upload-tips p {
  margin: 0 0 5px 0;
  font-size: 12px;
  color: #909399;
}

.certifications-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: flex-start;
}

.certification-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fafafa;
}

.cert-preview {
  width: 80px;
  height: 60px;
  object-fit: contain;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
}

.cert-placeholder {
  width: 80px;
  height: 60px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: white;
  transition: all 0.3s;
}

.cert-placeholder:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.product-config {
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 6px;
}

.product-config h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
}

:deep(.el-tabs__item) {
  height: 50px;
  line-height: 50px;
  font-size: 16px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

/* 视频上传样式 */
.video-upload-container {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.video-upload-area {
  width: 400px;
}

.video-preview {
  width: 400px;
  height: 225px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
}

/* 流程步骤样式 */
.steps-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.steps-header h3 {
  margin: 0;
  color: #303133;
}

.steps-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.step-card {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.step-number {
  font-weight: bold;
  color: #409eff;
  font-size: 16px;
}

.icon-upload-container {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.icon-preview {
  width: 60px;
  height: 60px;
  object-fit: contain;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
}

.icon-placeholder {
  width: 60px;
  height: 60px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.icon-placeholder:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.icon-placeholder .el-icon {
  font-size: 20px;
  color: #909399;
  margin-bottom: 2px;
}

.icon-placeholder span {
  font-size: 12px;
  color: #909399;
}
</style>